package HatterOsztalyok;

import android.content.Context;
import android.media.AudioManager;

/**
 * Kezeli az alkalmazás audio fókuszát
 */
public class AudioFocusHelper implements
		AudioManager.OnAudioFocusChangeListener {
	AudioManager mAM;
	MusicFocusable mFocusable;

	/**
	 * Konstruktor, inicializálja a változókat
	 */
	public AudioFocusHelper(Context ctx, MusicFocusable focusable) {
		mAM = (AudioManager) ctx.getSystemService(Context.AUDIO_SERVICE);
		mFocusable = focusable;
	}

	/**
	 * AudioFocus-t kér
	 * 
	 * @return Ha megkapta, True-t térít vissza, ellenkező esetben False-t
	 */
	public boolean requestFocus() {
		return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAM
				.requestAudioFocus(this, AudioManager.STREAM_MUSIC,
						AudioManager.AUDIOFOCUS_GAIN);
	}

	/**
	 * Feladja a Focus-t
	 * 
	 * @return
	 */
	public boolean abandonFocus() {
		return AudioManager.AUDIOFOCUS_REQUEST_GRANTED == mAM
				.abandonAudioFocus(this);
	}

	/**
	 * Ha megváltozik az audiofocus, akkor meghívja meghívja a MusicFocusable
	 * interfész megfelelő metódusait
	 */
	public void onAudioFocusChange(int focusChange) {
		if (mFocusable == null)
			return;
		switch (focusChange) {
		case AudioManager.AUDIOFOCUS_GAIN:
			mFocusable.onGainedAudioFocus();
			break;
		case AudioManager.AUDIOFOCUS_LOSS:
		case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT:
			mFocusable.onLostAudioFocus(false);
			break;
		case AudioManager.AUDIOFOCUS_LOSS_TRANSIENT_CAN_DUCK:
			mFocusable.onLostAudioFocus(true);
			break;
		default:
		}
	}
}